//
//  WeChatAuthManager.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 19.04.25.
//

import Foundation
import Alamofire

class WeChatAuthManager: NSObject, WXApiDelegate {
    let appId = "wx0f1e11bb110abf9d"
    let appSecret = "719721c8ba04be30c4986ed035d14c86"
    
    static let shared = WeChatAuthManager()
    private var completion: ((Result<[String: String], Error>) -> Void)?

    func login(completion: @escaping (Result<[String: String], Error>) -> Void) {
        self.completion = completion
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo"
        req.state = "koi_wx_login"
        WXApi.send(req)
    }

    func onResp(_ resp: BaseResp) {
        if let authResp = resp as? SendAuthResp, authResp.errCode == 0 {
            let code = authResp.code ?? ""
            getAccessToken(code: code) { accessResult in
                switch accessResult {
                case .success(let success):
                    let accessToken = success.access_token ?? ""
                    let openid = success.openid ?? ""
                    self.getUserInfo(accessToken: accessToken, openid: openid) { userInfoResult in
                        switch userInfoResult {
                        case .success(let success):
                            var params = [String : String]()
                            params["wx_unionid"] = success.unionid
                            params["wx_openid"] = success.openid
                            params["wx_nickname"] = success.nickname
                            params["wx_gender"] = String(success.sex ?? 0)
                            params["wx_headimgurl"] = success.headimgurl
                            params["wx_city"] = success.city
                            params["wx_country"] = success.country
                            params["wx_province"] = success.province
                            params["wx_privilege"] = success.privilege?.joined(separator: ",")
                            params["wx_access_token"] = accessToken
                            params["third_platform"] = "wx"
                            self.completion?(Result.success(params))
                        case .failure(let error):
                            self.completion?(Result.failure(error))
                        }
                    }
                case .failure(let error):
                    self.completion?(Result.failure(error))
                }
            }
        } else {
            completion?(.failure(NSError(domain: "WeChatAuth", code: -1)))
        }
    }
    
    private func getAccessToken(code: String, resultHandler: @escaping ((Result<WechatAccessResponse, AFError>) -> Void)) {
        let url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(appId)&secret=\(appSecret)&code=\(code)&grant_type=authorization_code"
        AF.request(url, method: .get).responseDecodable { (response:AFDataResponse<WechatAccessResponse>) in
            resultHandler(response.result)
        }
    }
    
    private func getUserInfo(accessToken: String, openid: String, resultHandler: @escaping ((Result<WechatUserInfoResponse, AFError>) -> Void)) {
        // GET https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID

        let url = "https://api.weixin.qq.com/sns/userinfo?access_token=\(accessToken)&openid=\(openid)"
        AF.request(url, method: .get).responseDecodable { (response:AFDataResponse<WechatUserInfoResponse>) in
            resultHandler(response.result)
        }
    }
}

struct WechatAccessResponse : Codable {
    /**
     * {
         "access_token": "ACCESS_TOKEN",
         "expires_in": 7200,
         "refresh_token": "REFRESH_TOKEN",
         "openid": "OPENID",
         "scope": "snsapi_userinfo",
         "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
       }
     */
    var access_token: String?
    var expires_in: Int?
    var refresh_token: String?
    var openid: String?
    var scope: String?
    var unionid: String?
}

struct WechatUserInfoResponse : Codable {
    /**
     {
       "openid": "OPENID",
       "nickname": "NICKNAME",
       "sex": 1,
       "province": "PROVINCE",
       "city": "CITY",
       "country": "COUNTRY",
       "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
       "privilege": ["PRIVILEGE1", "PRIVILEGE2"],
       "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
     }
     */
    var openid: String?
    var nickname: String?
    var sex: Int?
    var province: String?
    var city: String?
    var country: String?
    var headimgurl: String?
    var privilege: [String]?
    var unionid: String?
}
